<?php


namespace TDEngineOrm;

use TDengine\Connection;

class TDEngine
{
    /**
     * 数据库配置
     * @var array
     */
    protected static $config = [];
    /**
     * 数据库连接实例
     * @var array
     */
    protected static $instance = [];

    /**
     * @var int 查询次数
     */
    public static $queryTimes = 0;
    /**
     * 初始化配置参数
     * @access public
     * @param array $config 连接配置
     * @return void
     */
    public static function setConfig($config): void
    {
        
        self::$config = $config;

    }

    /**
     * 获取配置参数
     * @access public
     * @param string $name    配置参数
     * @param mixed  $default 默认值
     * @return mixed
     */
    public static function getConfig(string $name = '', $default = null)
    {
        if ('' === $name) {
            return self::$config;
        }
        return self::$config[$name] ?? $default;
    }
    /**
     * 数据库初始化，并取得数据库类实例
     * @access public
     * @param  mixed       $config 连接配置
     * @param  bool|string $name   连接标识 true 强制重新连接
     * @return Connection
     * @throws Exception
     */
    public static function connect($config = [], $name = false)
    {
        if (empty($name)) {
            $name = self::getConfig('default', 'TDEngine');
        }

        $config = self::getConnectionConfig($name);

        $type = !empty($config['type']) ? $config['type'] : 'TDEngine';
        if (false !== strpos($type, '\\')) {
            $class = $type;
        } else {
            $class = '\\TDEngineOrm\\connector\\' . ucfirst($type);
        }
        self::$instance[$name] = new $class($config);

        return self::$instance[$name];
    }

    /**
     * 获取连接配置
     * @param string $name
     * @return array
     */
    protected static function getConnectionConfig(string $name): array
    {
        $connections = self::getConfig('connections');

        return $connections[$name];
    }



    // 调用实际类的方法
    public  static function __callStatic($method, $params)
    {
        return call_user_func_array([self::connect(), $method], $params);
    }
}